import {
    LogoutOutlined,
    SettingOutlined,
    UserOutlined,
} from "@ant-design/icons";
import { history, useModel } from "@umijs/max";
import type { MenuProps } from "antd";
import { Spin } from "antd";
import { createStyles } from "antd-style";
import React, { useEffect, useState } from "react";
import { flushSync } from "react-dom";
import { outLogin } from "@/services/core/api";
import HeaderDropdown from "../HeaderDropdown";

export type GlobalHeaderRightProps = {
    menu?: boolean;
    children?: React.ReactNode;
};

export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({
    menu,
    children,
}) => {
    const useStyles = createStyles(({ token }) => ({
        action: {
            display: "flex",
            height: "48px",
            marginLeft: "auto",
            overflow: "hidden",
            alignItems: "center",
            padding: "0 8px",
            cursor: "pointer",
            borderRadius: token.borderRadius,
            "&:hover": {
                backgroundColor: token.colorBgTextHover,
            },
        },
    }));
    const { styles } = useStyles();
    const { initialState, setInitialState } = useModel("@@initialState");
    const [loading, setLoading] = useState(true);
    const [currentUser, setCurrentUser] = useState(initialState?.currentUser);

    useEffect(() => {
        // 确保初始化状态加载完成
        if (initialState !== undefined) {
            setCurrentUser(initialState.currentUser);
            setLoading(false);
        }
    }, [initialState]);

    const loginOut = async () => {
        try {
            await outLogin();
            flushSync(() => {
                setInitialState((s) => ({ ...s, currentUser: undefined }));
            });

            const { search, pathname } = window.location;
            const urlParams = new URLSearchParams(search);
            const redirect = urlParams.get("redirect");

            if (!redirect && pathname !== "/login") {
                history.replace({
                    pathname: "/login",
                    search: `redirect=${encodeURIComponent(pathname + search)}`,
                });
            }
        } catch (error) {
            console.error("退出登录失败:", error);
        }
    };

    const onMenuClick: MenuProps["onClick"] = (event) => {
        const { key } = event;
        if (key === "logout") {
            loginOut();
            return;
        }
        history.push(`/account/${key}`);
    };

    if (loading) {
        return (
            <span className={styles.action}>
                <Spin size="small" style={{ margin: "0 8px" }} />
            </span>
        );
    }

    if (!currentUser?.name) {
        return null; // 或者返回登录按钮
    }

    const menuItems: MenuProps["items"] = [
        ...(menu
            ? [
                  {
                      key: "center",
                      icon: <UserOutlined />,
                      label: "个人中心",
                  },
                  {
                      key: "settings",
                      icon: <SettingOutlined />,
                      label: "个人设置",
                  },
                  { type: "divider" as "divider" },
              ]
            : []),
        {
            key: "logout",
            icon: <LogoutOutlined />,
            label: "退出登录",
        },
    ];

    return (
        <HeaderDropdown
            menu={{
                selectedKeys: [],
                onClick: onMenuClick,
                items: menuItems,
            }}
        >
            {children}
        </HeaderDropdown>
    );
};
